package com.example.testapplication;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.SimpleClickListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class QuestionDetailActivity extends AppCompatActivity {

    String goldQuizId = "234025106261807104";
    View headView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail);

        ImageView ivBack = findViewById(R.id.ivBack);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        setHead();
        setListAnswer();

    }

    public void setHead() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://47.97.45.6:8092")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        final Reception reception = retrofit.create(Reception.class);
        Call<QuestionDetail> head = reception.getSimple(goldQuizId);
        LayoutInflater inflater = LayoutInflater.from(this);
        headView = inflater.inflate(R.layout.question_detail_head, null);
        head.enqueue(new Callback<QuestionDetail>() {
            @Override
            public void onResponse(@NonNull Call<QuestionDetail> call, @NonNull Response<QuestionDetail> response) {

                QuestionDetail all = response.body();
                TextView tvContent = headView.findViewById(R.id.tvquestionContent);
                tvContent.setText(all.getData().getContent());
                TextView tvCollectionNum = headView.findViewById(R.id.tvCollectionNum);
                tvCollectionNum.setText(all.getData().getCollectNum() + "收藏");
                TextView tvAnswerNum = headView.findViewById(R.id.tvAnswerNum);
                tvAnswerNum.setText(all.getData().getAnswerNum() + "回答");
                TextView tvCreateTime = headView.findViewById(R.id.tvCreateTime);
                String str = null;
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date time = format.parse(all.getData().getCreateTime());
                    String date = time.toString();
                    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", java.util.Locale.US);
                    Date datetime = sdf.parse(date);
                    str = new SimpleDateFormat("MM-dd HH:mm").format(datetime);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
                tvCreateTime.setText(str);

                ImageView ivHeadPicture1 = headView.findViewById(R.id.ivHeadPicture1);
                ImageView ivHeadPicture2 = headView.findViewById(R.id.ivHeadPicture2);
                ImageView ivHeadPicture3 = headView.findViewById(R.id.ivHeadPicture3);
                String url = "http://api.91jtg.com:8022/upload/images/";
                for (int i = 0; i < response.body().getData().getImageList().size(); i++) {
                    if (i == 0) {
                        Glide.with(QuestionDetailActivity.this).load(url + response.body().getData().getImageList().get(i).getImgPath()).into(ivHeadPicture1);
                    } else if (i == 1) {
                        Glide.with(QuestionDetailActivity.this).load(url + response.body().getData().getImageList().get(i).getImgPath()).into(ivHeadPicture2);
                    } else {
                        Glide.with(QuestionDetailActivity.this).load(url + response.body().getData().getImageList().get(i).getImgPath()).into(ivHeadPicture3);
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<QuestionDetail> call, @NonNull Throwable t) {
            }
        });
    }

    public void setListAnswer() {
        OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://47.97.45.6:8092")
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Reception reception = retrofit.create(Reception.class);
        reception.getListAnswerWithRxJava(goldQuizId, 1, 10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<QuestionListAnswer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(QuestionListAnswer questionListAnswer) {
                        getListAnswer(questionListAnswer);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

//        OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
////        Retrofit retrofit = new Retrofit.Builder()
////                .baseUrl("http://47.97.45.6:8092")
////                .callFactory(client)
////                .addConverterFactory(GsonConverterFactory.create())
////                .build();
////        final Reception reception = retrofit.create(Reception.class);
////        final Call<QuestionListAnswer> listAnswer = reception.getListAnswer(goldQuizId, 1, 10);
////        listAnswer.enqueue(new Callback<QuestionListAnswer>() {
////            @Override
////            public void onResponse(Call<QuestionListAnswer> call, Response<QuestionListAnswer> response) {
////                QuestionListAnswer all = response.body();
////                getListAnswer(all);
////
////            }
////
//            @Override
//            public void onFailure(Call<QuestionListAnswer> call, Throwable t) {
//
//            }
//        });
    }

    public void getListAnswer(final QuestionListAnswer questionListAnswer) {
        RecyclerView recyclerViewAnswer = findViewById(R.id.recyclerViewAnswer);
        QuestionDetailAdapter questionDetailAdapter = new QuestionDetailAdapter(R.layout.question_detail_answer, questionListAnswer.getData().getPageData());
        recyclerViewAnswer.setAdapter(questionDetailAdapter);
        recyclerViewAnswer.setLayoutManager(new LinearLayoutManager(QuestionDetailActivity.this));
        questionDetailAdapter.setEmptyView(R.layout.activity_question_detail, recyclerViewAnswer);
        questionDetailAdapter.addHeaderView(headView);
        recyclerViewAnswer.addItemDecoration(new DividerItemDecoration(QuestionDetailActivity.this, DividerItemDecoration.VERTICAL));

        final TextView tvCollection = findViewById(R.id.tvCollection);
        //收藏，关注，点赞
        final int[] i = {0};
        tvCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (i[0] == 0) {
                    Drawable top = ContextCompat.getDrawable(getApplicationContext(), R.mipmap.tf_sc_selected);
                    tvCollection.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
                    i[0]++;
                } else {
                    Drawable top = ContextCompat.getDrawable(getApplicationContext(), R.mipmap.tf_sc_default);
                    tvCollection.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
                    i[0]--;
                }
            }
        });

        recyclerViewAnswer.addOnItemTouchListener(new SimpleClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.tvFollow:
                        final TextView tvFollow = view.findViewById(R.id.tvFollow);
                        tvFollow.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (questionListAnswer.getData().getPageData().get(position).isFocus()) {
                                    tvFollow.setText("已关注");
                                    questionListAnswer.getData().getPageData().get(position).setFocus(false);
                                } else {
                                    tvFollow.setText("+ 关注");
                                    questionListAnswer.getData().getPageData().get(position).setFocus(true);
                                }
                            }
                        });
                        return;
                    case R.id.llAgree:
                        LinearLayout llAgree = view.findViewById(R.id.llAgree);
                        final ImageView ivAgree = view.findViewById(R.id.ivAgree);
                        llAgree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (questionListAnswer.getData().getPageData().get(position).isHasAgree()) {
                                    ivAgree.setImageResource(R.mipmap.tf_zt_default);
                                    questionListAnswer.getData().getPageData().get(position).setHasAgree(false);
                                } else {
                                    ivAgree.setImageResource(R.mipmap.tf_zt_selected);
                                    questionListAnswer.getData().getPageData().get(position).setHasAgree(true);
                                }
                            }
                        });
                        return;
                    default:
                }
            }

            @Override
            public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

}
